import {onUnmounted, ref} from 'vue';
import appConfig from '@/config/app.js';
import storage from "@/utils/storage.js";
import {useMessageStore} from '@/stores/message.ts';
import {ElMessage} from "element-plus";

export function useWebSocket() {
    const socket = ref(null);

    //连接socket
    const connect = () => {
        return new Promise((resolve, reject) => {
            const token = "Bearer " + storage.get('token')
            socket.value = new WebSocket(appConfig.wsHost + '/v1/ws?Authorization=' + token);

            //建立连接
            socket.value.onopen = () => {
                console.log('WebSocket Connected');
                resolve();
            };

            //接收消息
            socket.value.onmessage = (msg) => {
                handleReceiveMsg(msg);
            };

            //关闭连接
            socket.value.onclose = () => {
                console.log('WebSocket Closed');
            };

            //监听错误
            socket.value.onerror = (err) => {
                console.log('WebSocket Error:', err);
            }

        })

    };

    function handleReceiveMsg(msg) {
        let obj = JSON.parse(msg.data);
        const messageStore = useMessageStore();
        switch (obj.msg_type) {
            case "errMsg":
                ElMessage.warning(obj.msg_content);
                break;
            case 'chatMsg'://聊天消息
                messageStore.handleChatMsg(obj.msg_content);
                break;
            case "messageDetails"://聊天详情列表
                messageStore.handleMessageDetails(obj.msg_content);
                break;
            case "messageHistory"://聊天列表
                messageStore.handleMessageHistory(obj.msg_content);
                break;
        }
    }

    /**
     * 发送消息
     * @param msg
     * @returns {Promise<unknown>}
     */
    const sendMessage = (msg) => {
        console.log(msg);
        return new Promise(function (resolve, reject){
            if (socket.value && socket.value.readyState === WebSocket.OPEN) {
                socket.value.send(msg);
                resolve();
            }else {
                reject('WebSocket 未连接');
            }
        })
    };

    //清理socket连接
    onUnmounted(() => {
        if (socket.value) {
            socket.value.close()
        }
    });

    return {
        connect,
        sendMessage
    };
}